package com.zzxy.spring12.factory;

import com.zzxy.spring12.aspect.MyAspect;
import com.zzxy.spring12.service.IStudentService;
import com.zzxy.spring12.service.impl.StudentServiceImpl;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class MyBaanFactoryCglib {
   public static IStudentService createStudentService(){
       //1.target classes
       StudentServiceImpl studentService = new StudentServiceImpl();
       //2.advice
       MyAspect myAspect = new MyAspect();
       //3.weaving
       Enhancer enhancer = new Enhancer();
       enhancer.setSuperclass(studentService.getClass());
       enhancer.setCallback(new MethodInterceptor() {
           @Override
           public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
               myAspect.before();
               Object obj = methodProxy.invokeSuper(o, objects);
               myAspect.after();
               return obj;
           }
       });
       return (StudentServiceImpl) enhancer.create();
    }
}
